﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UtilZ.Dotnet.Ex.Attributes;
using UtilZ.Dotnet.Ex.Base;
using UtilZ.Dotnet.Ex.Log;
using UtilZ.Dotnet.Ex.Model;
using UtilZ.Dotnet.WindowsDesktopEx.Base;
using UtilZ.Dotnet.WindowsDesktopEx.Winform;

namespace DotnetWinFormApp
{
    public partial class FTestEmbedAppProcess : Form
    {
        public FTestEmbedAppProcess()
        {
            InitializeComponent();
        }

        private enum MainWindowQueryType
        {
            /// <summary>
            /// 类名
            /// </summary>
            [DisplayNameEx("类名")]
            ClassName,

            /// <summary>
            /// 标题
            /// </summary>
            [DisplayNameEx("标题")]
            Caption
        }

        private void FTestEmbedAppProcess_Load(object sender, EventArgs e)
        {
            var redirectAppenderToUI = (RedirectAppender)Loger.GetAppenderByName(null, "RedirectToUI");
            if (redirectAppenderToUI != null)
            {
                redirectAppenderToUI.RedirectOuput += RedirectLogOutput;
            }
            DropdownBoxHelper.BindingEnumToComboBox<MainWindowQueryType>(comboBoxQueryType, MainWindowQueryType.Caption);
        }

        private void RedirectLogOutput(object sender, RedirectOuputArgs e)
        {
            string str;
            try
            {
                str = string.Format("{0} {1}", DateTime.Now, e.Item.Content);
            }
            catch (Exception ex)
            {
                str = ex.Message;
            }

            logControl1.AddLog(str, e.Item.Level);
        }


        private WinformAppEmbedder _colorEmbedApp = null;
        private void btnColor_Click(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex != 0)
            {
                return;
            }

            if (this._colorEmbedApp != null)
            {
                return;
            }

            Loger.Info("--------------");
            this._colorEmbedApp = new WinformAppEmbedder(panelColor, @"E:\Soft\Color\Color.exe", false);
            this._colorEmbedApp.Start();
        }

        private WinformAppEmbedder _netAssistEmbedApp = null;
        private void btnNetAssist_Click(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex != 1)
            {
                return;
            }

            if (this._netAssistEmbedApp != null)
            {
                return;
            }

            Loger.Info("--------------");
            this._netAssistEmbedApp = new WinformAppEmbedder(panelNetAssist, @"E:\Soft\NetAssist.exe", false);
            this._netAssistEmbedApp.MainWindowHandleIndex = 2;
            //this._netAssistEmbedApp.MainWindowName = "网络调试助手";
            this._netAssistEmbedApp.GetMainWindowHandleMillisecondsTimeout = 20000;
            this._netAssistEmbedApp.Filter += _netAssistEmbedApp_Filter;
            this._netAssistEmbedApp.Start();
        }

        private void _netAssistEmbedApp_Filter(object sender, MainWindowHandleResolveEventArgs e)
        {
            //StringBuilder sb = new StringBuilder();
            //for (int i = 0; i < e.WindowHandleNames.Count; i++)
            //{
            //    if (sb.Length > 0)
            //    {
            //        sb.Append('/');
            //    }
            //    sb.Append(e.WindowHandleNames[i].Value.ToString());
            //}
            //Loger.Info(sb.ToString());

            //网络调试助手第一个句柄就可以,第二个就不行
            e.MainWindowHandle = e.WindowHandleNames[0].Value;

            //e.MainWindowHandle = e.WindowHandleNames.Last().Value;
            //e.MainWindowHandle = e.WindowHandleNames[1].Value;
        }


        private void FTestEmbedAppProcess_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this._colorEmbedApp != null)
            {
                this._colorEmbedApp.Dispose();
                this._colorEmbedApp = null;
            }


            if (this._netAssistEmbedApp != null)
            {
                this._netAssistEmbedApp.Dispose();
                this._netAssistEmbedApp = null;
            }
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            Process process = Process.GetProcessesByName("猎鹰100-B数据处理软件").FirstOrDefault();
            if (process != null)
            {
                List<NameValue<IntPtr>> list = WindowHelper.GetProcessWindowHandles(process, EncodingOptions.Unicode);

                foreach (NameValue<IntPtr> winHandle in list)
                {
                    int processId;
                    int threadId = WindowHelper.GetWindowThreadProcessId(winHandle.Value, out processId);
                    Process process2 = Process.GetProcessById(processId);
                }
            }


            IntPtr handle;
            var mainWindowQueryType = DropdownBoxHelper.GetEnumFromComboBox<MainWindowQueryType>(comboBoxQueryType);

            if (mainWindowQueryType == MainWindowQueryType.ClassName)
            {
                handle = WindowHelper.FindWindow(txtMainWindowName.Text, null);
            }
            else
            {
                handle = WindowHelper.FindWindow(null, txtMainWindowName.Text);
            }

            txtMainWindowHandle.Text = ConvertEx.ToHexadecimaString((long)handle);
            //var hadle1 = WindowHelper.FindWindow("notepad++", null);
            //var hadle2 = WindowHelper.FindWindow(null, @"*D:\tmp.txt - Notepad++");
        }


        private WinformAppEmbedder _testEmbedApp = null;
        private void btnEmbed_Click(object sender, EventArgs e)
        {
            if (this._testEmbedApp != null)
            {
                return;
            }

            //var winHandler = new IntPtr(Convert.ToInt32(txtMainWindowHandle.Text, 16));
            //this._testEmbedApp = new WinformAppEmbedder(groupBoxEmbed, winHandler);
            this._testEmbedApp = new WinformAppEmbedder(groupBoxEmbed, @"D:\猎鹰\猎鹰100-B数据处理软件11.04版本\猎鹰100-B数据处理软件11.04实时\猎鹰100-B数据处理软件.exe", false);
            this._testEmbedApp.MainWindowName = @"猎鹰 100-B";
            this._testEmbedApp.MainWindowHandleIndex = 2;
            this._testEmbedApp.GetMainWindowHandleMillisecondsTimeout = 3000;
            this._testEmbedApp.EmbedWindowOffset = new System.Drawing.Point(0, 35);
            this._testEmbedApp.WaitForExitMillisecondsTimeout = 100;
            this._testEmbedApp.Exited += _testEmbedApp_Exited;
            this._testEmbedApp.Start();
        }

        private void _testEmbedApp_Exited(object sender, EventArgs e)
        {
            this._testEmbedApp.Dispose();
            this._testEmbedApp = null;
        }
    }
}
